﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class SysManage_DataBak_DataBakManage : System.Web.UI.Page
{
    public string DataBackUpPath = ConfigurationManager.AppSettings["DataBackUp"];

    HsTec.Mobile.Green.SqlServerDAL.BakDataName MyBD = new HsTec.Mobile.Green.SqlServerDAL.BakDataName();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            RBackNameDataBind();

            SIP.Value = "127.0.0.1";
            DbLogon.Value = "sa";
            DbPsd.Value = "sa";
            DataBase.Value = "GreenData";
            BackName.Value = "GreenData" + DateTime.Now.ToString("yyyyMMdd");


            RSIP.Value = "127.0.0.1";
            RDbLogon.Value = "sa";
            RDbPsd.Value = "sa";
            RDataBase.Value = "GreenData";
            //RBackName.Value = "GreenData" + DateTime.Now.AddDays (-1).ToString("yyyyMMdd");

        }
    }


    protected void DataBack_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.SIP.Value == "")
            {
                ttt.Text = "请填写数据库IP地址......";
                return;
            }
            if (this.DbLogon.Value == "")
            {
                ttt.Text = "请填写数据库登录名......";
                return;
            }
            if (this.DbPsd.Value == "")
            {
                ttt.Text = "请填写数据库登录密码......";
                return;
            }
            if (this.DataBase.Value == "")
            {
                ttt.Text = "请填写源数据库名称......";
                return;
            } 
            
            if (BackName.Value.ToString().Trim() == "")
            {
                ttt.Text = "请填写备份数据库的名称......";
                return;
            }

            string ret = DbBackup(this.SIP.Value, this.DbLogon.Value, this.DbPsd.Value, this.DataBase.Value, BackName.Value.ToString().Trim());
            this.ttt.Text = ret;
        }
        catch (Exception ex)
        {
            this.ttt.Text = ex.Message;
        }

    }


    public void RBackNameDataBind()
    {
        RBackName.DataSource = MyBD.GetInfos("");
        RBackName.DataBind();
        RBackName.Items.Insert(0, "请选择");
        RBackName.Items[0].Value = "";
    }

    /// <summary>
    /// 数据库备份
    /// </summary>
    /// <returns>备份是否成功</returns>
    public string DbBackup(string IP,string Logon,string Psd,string dbName, string backupDBName)
    {
        string sIP = Page.Request.UserHostAddress;

        string sOrgID = "0";
        string sPersID ="0";
        try
        {
            sOrgID = (string)Session["Baimasoft_Dept_ID"];
            sPersID =(string)Session["Baimasoft_Pers_ID"];
        }
        catch 
        {
        }

        SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
        SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
        try
        {
            oSQLServer.LoginSecure = false;
            oSQLServer.Connect(IP, Logon, Psd);
            oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
            oBackup.Database = dbName;
            oBackup.Files = DataBackUpPath + backupDBName + ".bak";
            oBackup.BackupSetName = backupDBName;
            oBackup.BackupSetDescription = "数据库备份";
            oBackup.Initialize = true;
            oBackup.SQLBackup(oSQLServer);

            MyBD.InsertInfo(backupDBName, "1", sOrgID, sPersID, sIP);

            return "数据库已成功备份到：" + oBackup.Files ;
        }
        catch (Exception ex)
        {
            throw new Exception("数据库备份失败： " + ex.Message);
        }
        finally
        {
            oSQLServer.DisConnect();
        }
    }

    
    /// <summary>
    /// 数据恢复
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DataRestore_Click(object sender, EventArgs e)
    {
        if (this.RSIP.Value == "")
        {
            LRestore.Text = "请填写数据库IP地址......";
            return;
        }
        if (this.RDbLogon.Value == "")
        {
            LRestore.Text = "请填写数据库登录名......";
            return;
        }
        if (this.RDbPsd.Value == "")
        {
            LRestore.Text = "请填写数据库登录密码......";
            return;
        }
        if (this.RDataBase.Value == "")
        {
            LRestore.Text = "请填写源数据库名称......";
            return;
        } 

        if (this.RBackName.SelectedValue .ToString().Trim() == "0")
        {
            LRestore.Text = "请选择恢复文件名.....";
            return;
        }

        //杀死所有访问该数据库的进程
        //string conStr = "data source=" + this.SIP.Value + ";database=" + this.DataBase.Value + ";user id=" + this.DbLogon.Value + ";password=" + this.DbPsd.Value + "";
        //SqlConnection con = new SqlConnection(conStr);
        //string cmdText = String.Format("EXEC sp_KillThread @dbname='{0}'", this.DataBase.Value);
        //SqlCommand com = new SqlCommand(cmdText, con);
        try
        {
            //con.Open();
            //com.ExecuteNonQuery();
            //con.Close();
            //恢复数据库
            string ret = DbRestore(this.RSIP.Value, this.RDbLogon.Value, this.RDbPsd.Value, this.RDataBase.Value, this.RBackName.SelectedValue.ToString().Trim());
            this.LRestore.Text = ret;
        }
        catch (Exception ex)
        {
            //con.Close();
            this.LRestore.Text = ex.Message;
        }
    }


    public string DbRestore(string IP, string Logon, string Psd, string dbName, string backupDBName)
    {
        SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
        SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
        try
        {
            oSQLServer.LoginSecure = false;
            oSQLServer.Connect(IP, Logon, Psd);
            oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
            oRestore.Database = dbName;
            oRestore.Files = DataBackUpPath + backupDBName + ".bak";
            oRestore.FileNumber = 1;
            oRestore.ReplaceDatabase = true;
            oRestore.SQLRestore(oSQLServer);
            return "数据库" + dbName + "已经成功恢复!";
        }
        catch (Exception ex)
        {
            throw new Exception("数据库恢复失败: " + ex.Message);
        }
        finally
        {
            oSQLServer.DisConnect();
        }
    }


    /// <summary>
    /// 添加文件夹路径
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    //protected void AddFolderPath_Click(object sender, EventArgs e)
    //{
    //    if (FindFolder.HasFile)  //判断浏览文本框中有没有文件内容
    //    {
    //        string sfileFullName = FindFolder.PostedFile.FileName;
    //        int ifileFullName = sfileFullName.Length;
    //        int ifilename = System.IO.Path.GetFileName(sfileFullName).Length + 1;
    //        string sfilepath = sfileFullName.Remove(ifileFullName - ifilename, ifilename);

    //        BackUpFilePath.Value = sfilepath;
    //    }
    //    else
    //    {
    //    }
    //}

}